package util

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"xiaoniu-task/pkg"
)

// 由于本项目都是使用Post Json进行请求所以只需要写下面一个请求方法即可

// PostJson 发送post请求
func PostJson(url string, bodyMap map[string]interface{}) (r *pkg.Response, resErr error) {
	defer func() {
		p := recover()
		if p != nil {
			resErr = errors.New("请求错误")
		}
	}()
	bodyStr, err := json.Marshal(bodyMap)
	if err != nil {
		log.Println("请求参数转换成字符串时发生错误：", err)
		return pkg.NewFailResponse(err.Error()), nil
	}
	payload := strings.NewReader(string(bodyStr))
	client := &http.Client{}
	req, err := http.NewRequest(http.MethodPost, url, payload)
	if err != nil {
		log.Println("创建请求时发生错误：", err)
		return pkg.NewFailResponse(err.Error()), nil
	}
	req.Header.Add("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		log.Println("发送请求时发生错误：", err)
		return pkg.NewFailResponse(err.Error()), nil
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Println("读取响应时出现错误：", err)
		return pkg.NewFailResponse(err.Error()), nil
	}

	var response *pkg.Response
	response = new(pkg.Response)
	err = json.Unmarshal(body, response)
	if err != nil {
		log.Println("响应转换成实体类时出现错误：", err)
		return pkg.NewFailResponse(err.Error()), nil
	}
	return response, nil
}
